﻿using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace SuperGo.Silverlight {
	public partial class ButtonPanel {
		public ButtonPanel() {
			InitializeComponent();

			LayoutRoot = (Grid)__hiddenGrid.Parent;

			Loaded += new RoutedEventHandler(ButtonPanel_Loaded);
		}

		IList<FrameworkElement> _childElements;
		Grid LayoutRoot;
		
		void ButtonPanel_Loaded(object sender, RoutedEventArgs e) {
			_childElements = new List<FrameworkElement>(Children.Count);

			int userAddedChildIterator = 0;
			for (int realChildIterator = 0; realChildIterator < Children.Count; realChildIterator++) {
				FrameworkElement child = Children[realChildIterator] as FrameworkElement;
				if (child == null)
					continue;
				if (child.Name.StartsWith("__"))
					continue;

				// remove the child from the outermost Grid
				Children.RemoveAt(realChildIterator);
				realChildIterator--;
				
				// add a column to the "Visible" grid and put the child in that column
				__visibleGrid.ColumnDefinitions.Add(new ColumnDefinition());
				child.SetValue(ColumnProperty, userAddedChildIterator);
				__visibleGrid.Children.Add(child);
				
				// add the child to an ordered list of children
				_childElements.Add(child);
				
				userAddedChildIterator++;
			}
		}

		public void SetVisible(FrameworkElement element, bool visible) {
			element.SetVisible(visible, __visibleGrid, __hiddenGrid);

			// set the number of columns in the visible grid to the number of visible elements
			__visibleGrid.ColumnDefinitions.Clear();
			foreach (FrameworkElement child in __visibleGrid.Children) {
				__visibleGrid.ColumnDefinitions.Add(new ColumnDefinition());
			}

			int i = 0;
			foreach (FrameworkElement child in _childElements) {
				if (child.IsVisible()) {
					child.SetValue(ColumnProperty, i);
					i++;
				}
			}
		}
	}
}
